import { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { RootState } from '@/redux/store';
import { SignInTask, Course } from '@/types';
import '@/styles/pages/signInManage.scss';

// 这些服务函数需要在后续创建
import { getSignInTasks, createSignInTask } from '@/services/signIn';
import { getCourseList } from '@/services/course';

const SignInManage = () => {
  const [signInTasks, setSignInTasks] = useState<SignInTask[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [selectedCourseId, setSelectedCourseId] = useState<number | ''>('');
  const [isCreatingTask, setIsCreatingTask] = useState(false);
  const [classIds, setClassIds] = useState<number[]>([]);
  const [description, setDescription] = useState('');
  
  const { teacher } = useSelector((state: RootState) => state.auth);
  const navigate = useNavigate();

  useEffect(() => {
    fetchCourses();
  }, []);

  useEffect(() => {
    if (selectedCourseId) {
      fetchSignInTasks(Number(selectedCourseId));
    }
  }, [selectedCourseId]);

  // 将Unix时间戳转换为格式化的日期时间字符串
  const formatTimestamp = (timestamp: number | string): string => {
    if (!timestamp) return '-';
    
    // 如果是字符串且包含常规格式的日期，则直接返回
    if (typeof timestamp === 'string' && timestamp.includes('-')) {
      return timestamp;
    }
    
    try {
      // 将时间戳转换为毫秒（如果是秒级时间戳）
      const ts = typeof timestamp === 'string' 
        ? parseInt(timestamp) 
        : timestamp;
        
      const milliseconds = ts > 10000000000 ? ts : ts * 1000;
      
      // 创建日期对象并格式化
      const date = new Date(milliseconds);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return String(timestamp);
    }
  };

  const fetchSignInTasks = async (courseId: number) => {
    try {
      setLoading(true);
      setError('');
      
      const res = await getSignInTasks(courseId);
      console.log('获取签到任务结果:', res);
      
      if (res.code === 2000) {
        setSignInTasks(res.data?.tasks || []);
      } else {
        setError(res.message || '获取签到任务失败');
      }
    } catch (err: any) {
      console.error('获取签到任务列表出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const fetchCourses = async () => {
    try {
      setLoading(true);
      const res = await getCourseList();
      console.log('获取课程列表结果:', res);
      
      if (res.code === 2000) {
        setCourses(res.data?.courses || []);
        // 如果有课程，选择第一个
        if (res.data?.courses && res.data.courses.length > 0) {
          const firstCourseId = res.data.courses[0].id;
          setSelectedCourseId(firstCourseId);
          // 获取第一个课程的签到任务
          fetchSignInTasks(firstCourseId);
        }
      } else {
        setError(res.message || '获取课程列表失败');
      }
    } catch (err: any) {
      console.error('获取课程列表出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTask = async () => {
    if (!selectedCourseId) {
      setError('请选择课程');
      return;
    }

    // 默认时间设置
    const now = new Date();
    const endTime = new Date(now.getTime() + 30 * 60000); // 30分钟后
    const startTimeStr = now.toISOString().replace('T', ' ').substring(0, 19);
    const endTimeStr = endTime.toISOString().replace('T', ' ').substring(0, 19);
    
    try {
      setIsCreatingTask(true);
      setError('');
      
      // 使用课程相关的班级
      const selectedCourse = courses.find(c => c.id === Number(selectedCourseId));
      
      if (!selectedCourse) {
        setError('未找到选中的课程');
        return;
      }
      
      console.log('选中的课程:', selectedCourse);
      
      const classIdsList = selectedCourse.class_ids || [];
      
      if (classIdsList.length === 0) {
        console.warn('警告: 选中的课程没有关联班级');
      }
      
      console.log('创建签到任务参数:', {
        courseId: selectedCourseId,
        classIds: classIdsList,
        startTime: startTimeStr,
        endTime: endTimeStr,
        description: description || '课堂签到'
      });
      
      const res = await createSignInTask(
        Number(selectedCourseId),
        classIdsList,
        startTimeStr,
        endTimeStr,
        description || '课堂签到'
      );
      
      console.log('创建签到任务结果:', res);
      
      if (res.code === 2000) {
        // 刷新任务列表
        fetchSignInTasks(Number(selectedCourseId));
        setDescription('');
      } else {
        setError(res.message || '创建签到任务失败');
      }
    } catch (err: any) {
      console.error('创建签到任务出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsCreatingTask(false);
    }
  };

  const handleCourseChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const courseId = e.target.value ? Number(e.target.value) : '';
    setSelectedCourseId(courseId);
    if (courseId !== '') {
      fetchSignInTasks(Number(courseId));
    } else {
      setSignInTasks([]);
    }
  };
  
  const handleViewDetails = (taskId: number) => {
    navigate(`/sign-in/${taskId}`);
  };

  return (
    <div className="sign-in-manage-container">
      <h1 className="page-title">签到管理</h1>
      
      {error && <div className="error-message">{error}</div>}
      
      <div className="create-task-section">
        <h2>创建签到任务</h2>
        <div className="form-group">
          <select 
            value={selectedCourseId} 
            onChange={handleCourseChange}
            disabled={isCreatingTask || courses.length === 0}
          >
            <option value="">请选择课程</option>
            {courses.map((course) => (
              <option key={course.id} value={course.id}>
                {course.name} ({course.class_name})
              </option>
            ))}
          </select>
          <input
            type="text"
            placeholder="签到描述（选填）"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            disabled={isCreatingTask}
          />
          <button 
            className="btn-create" 
            onClick={handleCreateTask}
            disabled={isCreatingTask || !selectedCourseId}
          >
            {isCreatingTask ? '创建中...' : '创建签到任务'}
          </button>
        </div>
      </div>
      
      <div className="task-list-section">
        <h2>签到任务列表</h2>
        
        {loading ? (
          <div className="loading">加载中...</div>
        ) : signInTasks.length > 0 ? (
          <table className="task-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>课程</th>
                <th>班级</th>
                <th>开始时间</th>
                <th>结束时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {signInTasks.map((task) => (
                <tr key={task.id}>
                  <td>{task.id}</td>
                  <td>{task.course_name}</td>
                  <td>{task.class_name || '-'}</td>
                  <td className="time-cell">{formatTimestamp(task.start_time)}</td>
                  <td className="time-cell">{formatTimestamp(task.end_time)}</td>
                  <td>
                    <span className={`status ${task.status}`}>
                      {task.status === 'active' ? '进行中' : '已结束'}
                    </span>
                  </td>
                  <td>
                    <button 
                      className="btn-view-details"
                      onClick={() => handleViewDetails(task.id)}
                    >
                      查看详情
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="empty-tip">暂无签到任务</div>
        )}
      </div>
    </div>
  );
};

export default SignInManage;